package com.yenlien.traceyun.control.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.common.bean.UserInfo;
import com.yenlien.traceyun.control.dao.CompanyModelCategoryDao;
import com.yenlien.traceyun.control.dao.CustomAppVersionCategoryDao;
import com.yenlien.traceyun.control.dao.UpdateCompanyRecordDao;
import com.yenlien.traceyun.control.entity.CompanyModelCategory;
import com.yenlien.traceyun.control.entity.CustomAppVersionCategory;
import com.yenlien.traceyun.control.entity.UpdateCompanyRecord;
import com.yenlien.traceyun.control.interceptor.UserAuthUtil;
import com.yenlien.traceyun.control.service.CompanyMenuService;
import com.yenlien.traceyun.control.service.rest.CompanyRestService;
import com.yenlien.traceyun.control.service.rest.ResourceRestService;
import com.yenlien.traceyun.webase.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author: bigwangy@sina.com
 * @create: 2020-07-21
 * @description:
 **/
@RestController
@RequestMapping(value = "/company")
public class CompanyController extends BaseController {

    @Autowired
    private CompanyRestService companyRestService;

    @Autowired
    private CompanyMenuService companyMenuService;


    @Autowired
    private ResourceRestService resourceRestService;

    @Autowired
    private UpdateCompanyRecordDao updateCompanyRecordDao;

    @Autowired
    private CustomAppVersionCategoryDao customAppVersionCategoryDao;

    @Autowired
    private CompanyModelCategoryDao companyModelCategoryDao;


    @RequestMapping(value = "/findByList", method = RequestMethod.POST)
    public Object findByList(@RequestBody JSONObject jsonObject) {
        UserInfo userInfo = UserAuthUtil.getLoginUser();
        if (userInfo.getUserType().equals("GOV")) {
            jsonObject.put("parentId", userInfo.getCompanyId());
        }
        return companyRestService.findByList(jsonObject);
    }

    @RequestMapping(value = "/findById/{id}", method = RequestMethod.GET)
    public Object findById(@PathVariable String id) {
        return companyRestService.findById(id);
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public Object save(@RequestParam Map<String, Object> map, HttpServletRequest request) {
        List<MultipartFile> files = new ArrayList<>();
        if (!StringUtils.isEmpty(((MultipartHttpServletRequest) request).getFile("files"))) {
            files = ((MultipartHttpServletRequest) request).getFiles("files");
        }
        map.put("parentId", UserAuthUtil.getLoginUser().getCompanyId());
        return companyRestService.save(map, files);
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Object update(@RequestParam Map<String, Object> map, HttpServletRequest request) {
        List<MultipartFile> files = new ArrayList<>();
        if (!StringUtils.isEmpty(((MultipartHttpServletRequest) request).getFile("files"))) {
            files = ((MultipartHttpServletRequest) request).getFiles("files");
        }
        UpdateCompanyRecord record = new UpdateCompanyRecord();
        record.setCompanyId(map.get("id").toString());
        record.setDatetime(new Date());
        record.setOperation("修改");
        record.setPerson(UserAuthUtil.getLoginUser().getUsername());
        updateCompanyRecordDao.save(record);
        return companyRestService.update(map, files);
    }


    @RequestMapping(value = "/update2", method = RequestMethod.POST)
    public Object update2(@RequestBody Map<String, Object> map) {
        UpdateCompanyRecord record = new UpdateCompanyRecord();
        record.setCompanyId(map.get("id").toString());
        record.setDatetime(new Date());
        record.setOperation("修改");
        record.setPerson(UserAuthUtil.getLoginUser().getUsername());
        updateCompanyRecordDao.save(record);
        return companyRestService.update2(map);
    }





    @RequestMapping(value = "/load/updatecompany/record", method = RequestMethod.GET)
    public Object list(HttpServletRequest request) {
        return updateCompanyRecordDao.findAll(Sort.by(Sort.Direction.DESC, "datetime"));
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public Object delete(@PathVariable String id) {
        return companyRestService.delete(id);
    }

    /**
     * 加载企业拥有的资源
     *
     * @param id
     * @return
     */
    @GetMapping(value = "load/appmenus/{id}")
    public Object loadMenus(@PathVariable("id") String id) {
        JSONObject result = resourceRestService.loadAllCompanyAppMenu(id);
        result.put("categories", companyMenuService.loadCategory(id));
        return result;

    }

    /**
     * 设置企业资源
     *
     * @param params
     * @return
     */
    @PostMapping(value = "set/appmenus")
    public Object setmenus(@RequestBody JSONObject params) {
        return companyMenuService.setCommpany(params);
    }


    /**
     * 设置企业管理app
     *
     * @return
     */
    @RequestMapping(value = "/set/gov/setcustomapp", method = RequestMethod.POST)
    public Object setgovcustomapp(@RequestParam Map<String, Object> map, HttpServletRequest request) throws Exception {
        List<MultipartFile> files = new ArrayList<>();
        if (!StringUtils.isEmpty(((MultipartHttpServletRequest) request).getFile("files"))) {
            files = ((MultipartHttpServletRequest) request).getFiles("files");
        }
        return companyRestService.setGovConfig(map, files);
    }


    /**
     * 获取企业已绑定的以应用
     *
     * @param companyId
     * @return
     */
    @GetMapping(value = "/get/customapp/{companyId}")
    public Object getCustomApp(@PathVariable String companyId) {
        return companyRestService.getCustomApp(companyId);
    }

    /**
     * 获取政府配置
     *
     * @return
     */
    @GetMapping(value = "/get/govconfig/{companyId}")
    public Object getGovConfig(@PathVariable String companyId) {
        return companyRestService.getGovConfig(companyId);
    }

    /**
     * 根据type加载所有
     *
     * @param type
     * @return
     */
    @RequestMapping(value = "/findByType/{type}", method = RequestMethod.GET)
    public Object findAllGov(@PathVariable String type) {
        return companyRestService.companyType(type);
    }

    /**
     * 设置企业管理app
     *
     * @return
     */
    @RequestMapping(value = "/company/setcustomapp", method = RequestMethod.POST)
    public Object setCustomAppVersion(@RequestBody JSONArray array) throws Exception {
        if (array != null && array.size() > 0) {
            Set<String> versionids = new HashSet<>();
            String companyId = null;
            for (int i = 0; i < array.size(); i++) {
                JSONObject item = array.getJSONObject(i);
                versionids.add(item.getString("customAppVersionId"));
                companyId = item.getString("companyId");
            }
            List<CustomAppVersionCategory> categories = customAppVersionCategoryDao.findByCustomAppVersionIdIn(versionids);
            companyModelCategoryDao.deleteByCompanyId(companyId);
            if (categories != null && categories.size() > 0) {
                List<CompanyModelCategory> modelCategories = new ArrayList<>();
                for (CustomAppVersionCategory customAppVersionCategory : categories) {
                    CompanyModelCategory companyModelCategory = new CompanyModelCategory();
                    companyModelCategory.setCategoryId(customAppVersionCategory.getCategoryId());
                    companyModelCategory.setCompanyId(companyId);
                    modelCategories.add(companyModelCategory);
                }
                companyModelCategoryDao.saveAll(modelCategories);
            }
        }
        companyRestService.setCustomAppVersion(array);
        return success("ok");
    }

    /**
     * 审核
     *
     * @param params
     * @return
     */
    @PostMapping(value = "/examined")
    public Object examined(@RequestBody JSONObject params) {
        params.put("person", UserAuthUtil.getLoginUser().getUsername());
        return companyRestService.examined(params);
    }

    /**
     * 审核记录
     *
     * @param
     * @return
     */
    @GetMapping(value = "/examinedlist/{companyId}")
    public Object examinedlist(@PathVariable("companyId") String companyId) {
        return companyRestService.examinedlist(companyId);
    }

    /**
     * 修改授权时间
     *
     * @return
     */
    @PostMapping(value = "/change/expiretime")
    public Object chenageExpiretime(@RequestBody JSONObject params) {
        companyRestService.chenageExpiretime(params);
        UpdateCompanyRecord record = new UpdateCompanyRecord();
        record.setCompanyId(params.getString("companyId"));
        record.setDatetime(new Date());
        record.setOperation("修改");
        record.setPerson(UserAuthUtil.getLoginUser().getUsername());
        updateCompanyRecordDao.save(record);
        return success("ok");
    }

    /**
     * 获取政府配置
     *
     * @return
     */
    @GetMapping(value = "/get/update/{companyId}")
    public Object updatecommpanyrecord(@PathVariable("companyId") String companyId) {
        List<UpdateCompanyRecord> list = updateCompanyRecordDao.findByCompanyId(companyId, Sort.by(Sort.Direction.DESC, "datetime"));
        return list;
    }

    /**
     * 重置密码
     */
    @PostMapping(value = "/resetpassword")
    public Object resetPassword(@RequestBody JSONObject param) {
        companyRestService.resetPassword(param);
        return success("ok");
    }

    /**
     * 获取政府配置
     *
     * @return
     */
    @GetMapping(value = "/get/child")
    public Object getchild() {
        String companyId = UserAuthUtil.getLoginUser().getCompanyId();
        return companyRestService.getchild(companyId);
    }
}
